<script setup lang="ts">
import { theme, Button, Typography, message } from 'ant-design-vue'
import { SendOutlined, MessageOutlined, UserOutlined } from '@ant-design/icons-vue'
import { computed, ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import roleService, { type ExtendedRole } from '@/api/roleService'
import { Codewin } from '@/api/generated/Codewin'
import type { ConversationCreateRequest, MessageInsertRequest } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores'
import VoiceButton from '@/components/RoleChat/VoiceButton.vue'
import TTSPlayButton from '@/components/Common/TTSPlayButton.vue'
import ConversationSidebar from '@/components/RoleChat/ConversationSidebar.vue'
import RoleCardList from '@/components/RoleChat/RoleCardList.vue'

const { Title, Text } = Typography
const { token } = theme.useToken()

const styles = computed(() => {
  return {
    'layout': {
      'width': '100%',
      'min-width': '800px',
      'max-width': '1200px',
      'height': 'max(100vh, 1200px)', // 改为全屏高度
      'border-radius': `${token.value.borderRadius}px`,
      'display': 'flex',
      'flex-direction': 'column',
      'margin': '0 auto',
      'background': `${token.value.colorBgContainer}`,
      'font-family': `AlibabaPuHuiTi, ${token.value.fontFamily}, sans-serif`,
    },
    'mainArea': {
      'flex': 1,
      'display': 'flex',
      'flex-direction': 'column',
      'height': '100%',
      'min-height': 0, // 确保flex子元素可以收缩
    },
    'contentArea': {
      'flex': 1,
      'overflow': 'hidden', // 改为hidden，让子元素处理滚动
      'background': `${token.value.colorBgContainer}`,
      'min-height': 0, // 确保flex子元素可以收缩
    },
  } as const
})

defineOptions({ name: 'RoleChat' })

// 路由相关
const route = useRoute()
const router = useRouter()

// 接收路由参数
interface Props {
  conversationId?: string
}

const props = defineProps<Props>()

// ==================== Chat State ====================
const chatMessages = ref<Array<{id: string, content: string, sender: 'user' | 'ai', timestamp: Date, audioUrl?: string}>>([])
const chatInput = ref('')
const isChatting = ref(false)
const selectedChatRole = ref<ExtendedRole | null>(null)
const chatRoles = ref<ExtendedRole[]>([])
const loadingChatRoles = ref(false)
const currentConversationId = ref<string | null>(null)
const isVoiceRecording = ref(false)
const isStreamingAI = ref(false)

// 深度思考和网络搜索状态
const isThinking = ref(false)
const isSearch = ref(false)

// 历史会话列表相关状态
const conversationHistory = ref<Array<{
  id: string
  title: string
  roleId: string
  roleName: string
  lastMessage: string
  lastMessageTime: string
  createdAt: string
}>>([])
const loadingConversations = ref(false)

// 消息分页状态管理
const messagePageInfo = ref<{ pageNo: number; hasMore: boolean; loading: boolean }>({
  pageNo: 1,
  hasMore: true,
  loading: false
})

// 聊天消息区域引用
const chatMessagesAreaRef = ref<HTMLElement>()

// TTS相关状态
const isTTSGenerating = ref(false)

// 流式输出结束检测定时器
let streamEndTimer: number | null = null

// 处理语音转文本结果
const handleTranscriptionUpdate = (text: string, audioUrl: string) => {
  // 将实际转录的文本赋值给输入框
  if (text && text.trim()) {
    chatInput.value = text.trim()
    console.log('语音转文本结果已更新到输入框:', text.trim())
    console.log('音频URL:', audioUrl)

    // 显示成功提示
    // message.success(`语音识别成功: ${text.trim()}`)
  } else {
    console.warn('语音转文本结果为空')
    message.warning('语音识别结果为空，请重试')
  }
  // 不自动发送，等待用户手动点击发送按钮
}

// 处理语音录制开始
const handleRecordingStart = () => {
  isVoiceRecording.value = true
  console.log('开始录音')
}

// 处理语音录制停止
const handleRecordingStop = () => {
  isVoiceRecording.value = false
  console.log('停止录音')
}

// 处理语音录制错误
const handleVoiceError = (error: string) => {
  isVoiceRecording.value = false
  message.error(`语音录制错误: ${error}`)
}

// TTS接口调用函数
const callTTSAPI = async (text: string, voiceModel: string = '5'): Promise<string | null> => {
  if (!text?.trim()) {
    return null
  }

  try {
    isTTSGenerating.value = true

    // 获取当前选中角色的语音ID，如果没有则使用默认值
    const voiceId = selectedChatRole.value?.voiceId || voiceModel;

    // 创建WebSocket连接进行TTS处理，添加token鉴权和语音模型参数
    const token = authStore.token
    const wsUrl = `wss://www.codewin.top/codewin/ai/speech/tts-stream?token=${encodeURIComponent(token || '')}&voice_id=${encodeURIComponent(voiceId)}`

    return new Promise<string | null>((resolve, reject) => {
      const ws = new WebSocket(wsUrl)
      ws.binaryType = 'blob'
      let audioUrl: string | null = null

      ws.onopen = () => {
        // 发送文本内容进行TTS转换
        ws.send(JSON.stringify(text.trim()))
      }

      ws.onmessage = async (event) => {
        try {
          if (event.data instanceof Blob) {
            // 处理音频Blob数据，这里简化处理，实际应该将音频上传到服务器获取URL
            // 为了演示，我们返回一个模拟的音频URL
            audioUrl = `http://47.96.166.5:9000/aigc/tts_${Date.now()}.mp3`
          } else if (typeof event.data === 'string') {
            const data = JSON.parse(event.data)

            if (data.status === 'complete') {
              ws.close()
            } else if (data.error) {
              reject(new Error(data.error))
            }
          }
        } catch (error) {
          reject(new Error('处理TTS响应数据失败'))
        }
      }

      ws.onclose = () => {
        resolve(audioUrl)
      }

      ws.onerror = (error) => {
        console.error('TTS WebSocket连接错误:', error)
        reject(new Error('TTS服务连接失败'))
      }
    })

  } catch (error) {
    console.error('TTS调用失败:', error)
    return null
  } finally {
    isTTSGenerating.value = false
  }
}



// 生成流式AI回复
const generateStreamResponse = async (userMessage?: string) => {
  try {
    if (!selectedChatRole.value) {
      throw new Error('未选择聊天角色')
    }

    isStreamingAI.value = true
    isChatting.value = true

    // 根据角色名称生成不同风格的提示词
    let rolePrompt = userMessage || ''


    // 创建WebSocket连接进行流式输出，添加token鉴权和会话ID
    const token = authStore.token
    const conversationId = currentConversationId.value
    const wsUrl = `wss://www.codewin.top/codewin/ai/chat/qwen-stream?token=${encodeURIComponent(token || '')}&conversationId=${encodeURIComponent(conversationId || '')}&isThinking=${isThinking.value}&isSearch=${isSearch.value}`
    const ws = new WebSocket(wsUrl)

    return new Promise<void>((resolve, reject) => {
      let aiResponse = ''
      let aiMessageId = ''

      ws.onopen = () => {
        // 发送消息
        ws.send(rolePrompt)

        // 添加AI消息占位符
        aiMessageId = Date.now().toString()
        addChatMessage('', 'ai')
      }

      ws.onmessage = (event) => {
        try {
          // 清除之前的结束检测定时器
          if (streamEndTimer) {
            clearTimeout(streamEndTimer)
            streamEndTimer = null
          }

          // 尝试解析JSON格式的消息
          let data
          try {
            data = JSON.parse(event.data)
          } catch (jsonError) {
            // 如果不是JSON格式，直接作为文本流处理
            const textContent = event.data
            if (textContent && textContent.trim() && isStreamingAI.value) {
              aiResponse += textContent
              // 更新最后一条AI消息
              if (chatMessages.value.length > 0) {
                const lastMessage = chatMessages.value[chatMessages.value.length - 1]
                if (lastMessage && lastMessage.sender === 'ai') {
                  lastMessage.content = aiResponse
                }
              }

              // 设置结束检测定时器（1秒内没有新数据则认为结束）
              streamEndTimer = window.setTimeout(() => {
                if (isStreamingAI.value) {
                  ws.close()
                }
              }, 1000)
            } else if (!textContent || !textContent.trim()) {
              // 如果是空消息，可能是服务器的结束信号，直接结束流式输出
              if (isStreamingAI.value && aiResponse.length > 0) {
                ws.close()
              }
            }
            return
          }

          // 处理JSON格式的消息
          if (data.type === 'chunk' && data.content) {
            aiResponse += data.content
            // 更新最后一条AI消息
            if (chatMessages.value.length > 0) {
              const lastMessage = chatMessages.value[chatMessages.value.length - 1]
              if (lastMessage && lastMessage.sender === 'ai') {
                lastMessage.content = aiResponse
              }
            }

            // 设置结束检测定时器（1秒内没有新数据则认为结束）
            streamEndTimer = window.setTimeout(() => {
              if (isStreamingAI.value) {
                ws.close()
              }
            }, 1000)
          } else if (data.type === 'end') {
            // 流式输出结束
            ws.close()
          } else if (data.type === 'error') {
            throw new Error(data.message || '服务器返回错误')
          }
        } catch (error) {
          console.error('处理WebSocket消息失败:', error)
          reject(error)
        }
      }

      ws.onclose = async () => {
        isStreamingAI.value = false
        isChatting.value = false

        // 清理结束检测定时器
        if (streamEndTimer) {
          clearTimeout(streamEndTimer)
          streamEndTimer = null
        }

        // 保存AI回复到数据库
        if (aiResponse && currentConversationId.value !== null) {
          try {
            // 调用TTS接口生成AI消息的语音URL
            let audioUrl: string | null = null
            try {
              audioUrl = await callTTSAPI(aiResponse)
            } catch (ttsError) {
              console.warn('TTS生成失败，将不包含语音:', ttsError)
            }

            // 插入AI消息，包含生成的audioURL
            const insertRequest: MessageInsertRequest = {
              conversationId: currentConversationId.value as string,
              content: aiResponse,
              type: 1, // AI回复
              audioUrl: audioUrl || undefined // 如果TTS生成成功则包含audioURL
            }

            await api.insertMessage(insertRequest)

            // 插入消息后，重新加载历史消息以确保数据同步
            await loadHistoryMessages()
          } catch (error) {
            console.error('保存AI回复失败:', error)
            message.error('保存AI回复失败')
          }
        }

        resolve()
      }

      ws.onerror = (error) => {
        console.error('WebSocket连接错误:', error)
        isStreamingAI.value = false
        isChatting.value = false

        // 清理结束检测定时器
        if (streamEndTimer) {
          clearTimeout(streamEndTimer)
          streamEndTimer = null
        }

        reject(new Error('WebSocket连接失败'))
      }
    })

  } catch (error) {
    isStreamingAI.value = false
    isChatting.value = false
    console.error('生成AI回复失败:', error)
    message.error('生成AI回复失败，请重试')
    throw error
  }
}

// ==================== API Setup ====================
const authStore = useAuthStore()
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  securityWorker: () => ({
    headers: {
      Authorization: `Bearer ${authStore.token}`
    }
  })
})

// ==================== Chat Functions ====================
const loadChatRoles = async () => {
  try {
    loadingChatRoles.value = true

    // 同时请求普通角色列表和默认角色列表
    const [normalResponse, defaultResponse] = await Promise.all([
      roleService.getRoleList({
        pageNo: 1,
        pageSize: 20,
        keyword: '',
        category: '',
        tags: []
      }),
      roleService.getDefaultRoles({
        pageNo: 1,
        pageSize: 50 // 获取更多默认角色
      })
    ])

    console.log("加载普通角色列表成功:", normalResponse)
    console.log("加载默认角色列表成功:", defaultResponse)

    // 为默认角色添加标识字段
    const defaultRoles = defaultResponse.records.map(role => ({
      ...role,
      isDefault: true, // 添加默认角色标识
      createAt: role.createdAt || new Date().toISOString() // 确保有createAt字段
    }))

    // 为普通角色添加createAt字段
    const normalRoles = normalResponse.records.map(role => ({
      ...role,
      createAt: role.createdAt || new Date().toISOString() // 确保有createAt字段
    }))

    // 合并普通角色和默认角色
    const allRoles = [...normalRoles, ...defaultRoles]

    chatRoles.value = allRoles
  } catch (error) {
    console.error('加载聊天角色失败:', error)
    message.error('加载聊天角色失败，请重试')
    // 使用默认角色作为备选
    chatRoles.value = [] as ExtendedRole[]
  } finally {
    loadingChatRoles.value = false
  }
}

// 加载历史会话列表
const loadConversationHistory = async () => {
  try {
    loadingConversations.value = true

    // 直接传递扁平化的分页参数
    const response = await api.request({
      path: '/codewin/conversation/list',
      method: 'GET',
      query: {
        pageNo: 1,
        pageSize: 100 // 加载最近100个会话
      },
      secure: true
    })

    if (response.data?.code === 0 && response.data?.data?.list) {
      conversationHistory.value = response.data.data.list.map((conv: any) => ({
        id: conv.id?.toString() || '',
        title: conv.title || `与${conv.roleName || '未知角色'}的对话`,
        roleId: conv.roleId?.toString() || '',
        roleName: conv.roleName || '未知角色',
        lastMessage: conv.lastMessage || '暂无消息',
        lastMessageTime: conv.lastMessageTime || conv.createdAt || '',
        createdAt: conv.createdAt || ''
      }))
    } else {
      conversationHistory.value = []
    }
  } catch (error) {
    console.error('加载历史会话失败:', error)
    conversationHistory.value = []
    // 不显示错误提示，因为这不是关键功能
  } finally {
    loadingConversations.value = false
  }
}

// 点击历史会话跳转
const selectConversation = async (conversation: any) => {
  try {
    // 跳转到对应的会话页面
    await router.push(`/role-chat/${conversation.id}`)
  } catch (error) {
    console.error('跳转会话失败:', error)
    message.error('跳转会话失败，请重试')
  }
}

// 删除会话处理函数
const handleDeleteConversation = async (conversationId: string) => {
  try {
    const response = await api.deleteConversation(conversationId)

    if (response.data?.code === 0) {
      message.success('删除会话成功')

      // 如果删除的是当前会话，跳转回角色选择页面
      if (conversationId === currentConversationId.value) {
        selectedChatRole.value = null
        chatMessages.value = []
        currentConversationId.value = null
        await router.push('/role-chat')
      }

      // 重新加载会话列表
      await loadConversationHistory()
    } else {
      throw new Error(response.data?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除会话失败:', error)
    message.error('删除会话失败，请重试')
  }
}



// 加载历史消息
const loadHistoryMessages = async (loadMore = false) => {
  if (!currentConversationId.value) return

  try {
    // 如果正在加载或没有更多数据，直接返回
    if (messagePageInfo.value.loading || (!loadMore && !messagePageInfo.value.hasMore && chatMessages.value.length > 0)) {
      return
    }

    messagePageInfo.value.loading = true

    const currentPageNo = loadMore ? messagePageInfo.value.pageNo + 1 : 1

    // 直接传递扁平化的分页参数
    const response = await api.request({
      path: `/codewin/conversation/${currentConversationId.value}/messages`,
      method: 'GET',
      query: {
        pageNo: currentPageNo,
        pageSize: 10 // 一次查询10条消息
      },
      secure: true
    })

    if (response.data?.code === 0 && response.data?.data?.list) {
      // 将历史消息转换为本地消息格式
      const historyMessages = response.data.data.list.map((msg: any) => ({
        id: msg.id?.toString() || Date.now().toString(),
        content: msg.content || '',
        sender: msg.type === 0 ? 'user' : 'ai' as 'user' | 'ai',
        timestamp: new Date((msg.createdAt ? new Date(msg.createdAt).getTime() + 8 * 60 * 60 * 1000 : Date.now())),
        audioUrl: msg.audioUrl || undefined
      }))

      if (loadMore) {
        // 加载更多时，将新消息插入到现有消息列表的开头
        chatMessages.value = [...historyMessages, ...chatMessages.value]
        messagePageInfo.value.pageNo = currentPageNo
      } else {
        // 初始加载时，直接设置消息列表并按时间顺序排序
        chatMessages.value = historyMessages.sort((a: any, b: any) => a.timestamp.getTime() - b.timestamp.getTime())
        messagePageInfo.value.pageNo = 1
      }

      // 更新是否还有更多数据
      messagePageInfo.value.hasMore = historyMessages.length === 10

      // 如果是初始加载且不是加载更多，滚动到底部
      if (!loadMore) {
        nextTick(() => {
          scrollToBottom()
        })
      }
    } else {
      if (!loadMore) {
        chatMessages.value = []
      }
    }
  } catch (error) {
    console.error('加载历史消息失败:', error)
    if (!loadMore) {
      chatMessages.value = []
    }
    // 不显示错误提示，因为这不是关键功能
  } finally {
    messagePageInfo.value.loading = false
  }
}

// 加载更多历史消息
const loadMoreMessages = async () => {
  if (!currentConversationId.value) return

  if (messagePageInfo.value.loading || !messagePageInfo.value.hasMore) return

  // 记录当前滚动位置和第一条消息的位置
  const chatMessagesArea = chatMessagesAreaRef.value
  if (!chatMessagesArea) return

  const firstMessage = chatMessagesArea.querySelector('.message-item')
  const scrollTop = chatMessagesArea.scrollTop
  const scrollHeight = chatMessagesArea.scrollHeight

  await loadHistoryMessages(true)

  // 恢复滚动位置，保持用户的阅读位置
  await nextTick()
  if (firstMessage) {
    const newScrollHeight = chatMessagesArea.scrollHeight
    const heightDiff = newScrollHeight - scrollHeight
    chatMessagesArea.scrollTop = scrollTop + heightDiff
  }
}

// 滚动事件处理
const handleScroll = () => {
  const chatMessagesArea = chatMessagesAreaRef.value
  if (!chatMessagesArea || !currentConversationId.value) return

  // 检测是否滚动到顶部（留一些缓冲区域）
  if (chatMessagesArea.scrollTop <= 50) {
    loadMoreMessages()
  }
}

const selectChatRole = async (role: ExtendedRole) => {
  try {
    if (!role.id) {
      throw new Error('角色ID无效')
    }

    selectedChatRole.value = role;
    console.log('selectChatRole - selectedRole:', selectedChatRole.value);
    chatMessages.value = []
    currentConversationId.value = null

    // 重置分页状态
    messagePageInfo.value = { pageNo: 1, hasMore: true, loading: false }

    // 创建新会话
    const createRequest: ConversationCreateRequest = {
      roleId: role.id as string,
      title: `与${role.roleName}的对话`
    }

    const response = await api.createConversation(createRequest)
    if (response.data?.code === 0 && response.data?.data?.conversationId) {
      currentConversationId.value = response.data.data.conversationId;

      // 跳转到动态路由
      await router.push(`/role-chat/${currentConversationId.value}`)

      // 添加角色的开场白
      const welcomeMessage = `你好！我是${role.roleName}。${role.prompt}。让我们开始对话吧！`
      addChatMessage(welcomeMessage, 'ai')

      // 将开场白插入到数据库
      await api.insertMessage({
        conversationId:currentConversationId.value as string,
        content: welcomeMessage,
        type: 1 // AI回复
      })

      // 插入消息后，重新加载历史消息以确保数据同步
      await loadHistoryMessages()

      // 重新加载历史会话列表以显示新创建的会话
      await loadConversationHistory()
    } else {
      throw new Error(response.data?.message || '创建会话失败')
    }
  } catch (error) {
    console.error('选择角色失败:', error)
    message.error('创建会话失败，请重试')
    selectedChatRole.value = null
  }
}

// 滚动到消息底部
const scrollToBottom = () => {
  if (chatMessagesAreaRef.value) {
    chatMessagesAreaRef.value.scrollTop = chatMessagesAreaRef.value.scrollHeight
  }
}

const addChatMessage = (content: string, sender: 'user' | 'ai') => {
  chatMessages.value.push({
    id: Date.now().toString(),
    content,
    sender,
    timestamp: new Date()
  })

  // 添加消息后滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}

const sendChatMessage = async () => {
  if (!chatInput.value.trim() || !selectedChatRole.value || !currentConversationId.value) return

  const userMessage = chatInput.value.trim()

  // 显示用户消息
  addChatMessage(userMessage, 'user')
  chatInput.value = ''

  isChatting.value = true

  try {
    // 插入用户消息到数据库，携带固定的线上音频URL
    if (userMessage && currentConversationId.value !== null) {
      const fixedAudioUrl = ''
      const insertRequest: MessageInsertRequest = {
        conversationId: currentConversationId.value as string,
        content: userMessage,
        type: 0, // 用户消息
        audioUrl: fixedAudioUrl // 始终携带固定的线上音频URL
      }

      await api.insertMessage(insertRequest)

      // 插入用户消息后，重新加载历史消息以确保数据同步
      await loadHistoryMessages()
    }

    // 使用流式输出进行AI回复
    await generateStreamResponse(userMessage)

  } catch (error) {
    console.error('发送消息失败:', error)
    message.error('发送消息失败，请重试')
  } finally {
    isChatting.value = false
  }
}

const clearChat = () => {
  chatMessages.value = []
  // 重置分页状态
  messagePageInfo.value = { pageNo: 1, hasMore: true, loading: false }
  if (selectedChatRole.value) {
    // 重新添加开场白
    addChatMessage(`你好！我是${selectedChatRole.value.roleName}。${selectedChatRole.value.prompt}。让我们开始对话吧！`, 'ai')
  }
}

const backToRoleSelection = () => {
  selectedChatRole.value = null
  chatMessages.value = []
  currentConversationId.value = null
  // 重置分页状态
  messagePageInfo.value = { pageNo: 1, hasMore: true, loading: false }
  router.push('/role-chat')
}

// 通过会话ID获取会话详情
const getConversationDetails = async (conversationId: string) => {
  try {
    // 通过会话列表API查找指定会话
    // 直接传递扁平化的分页参数
    const response = await api.request({
      path: '/codewin/conversation/list',
      method: 'GET',
      query: {
        pageNo: 1,
        pageSize: 100 // 获取足够多的会话来查找目标会话
      },
      secure: true
    })

    if (response.data?.code === 0 && response.data?.data?.list) {
      const conversation = response.data.data.list.find(
        (conv: any) => conv.id?.toString() === conversationId
      )

      if (conversation) {
        return {
          id: conversation.id,
          title: conversation.title,
          roleId: conversation.roleId,
          roleName: conversation.roleName,
          lastMessage: conversation.lastMessage,
          lastMessageTime: conversation.lastMessageTime
        }
      }
    }
    return null
  } catch (error) {
    console.error('获取会话详情失败:', error)
    return null
  }
}

// 根据路由参数加载会话
const loadConversationFromRoute = async () => {
  const conversationId = props.conversationId || route.params.conversationId as string

  if (conversationId && conversationId !== currentConversationId.value) {
    try {
      currentConversationId.value = conversationId

      // 重置分页状态
      messagePageInfo.value = { pageNo: 1, hasMore: true, loading: false }

      // 首先获取会话详情
      const conversationDetails = await getConversationDetails(conversationId)

      if (conversationDetails) {
        // 根据会话中的角色信息设置当前角色
        if (conversationDetails.roleId) {
          // 从已加载的角色列表中找到对应角色
          const matchedRole = chatRoles.value.find(role => role.id === conversationDetails.roleId)
          if (matchedRole) {
            selectedChatRole.value = matchedRole
          } else {
            // 如果在当前角色列表中找不到，创建一个临时角色对象
            selectedChatRole.value = {
              id: conversationDetails.roleId,
              roleName: conversationDetails.roleName || '未知角色',
              prompt: '',
              avatarUrl: '',
              createAt: ''
            } as ExtendedRole
          }
        }

        // 加载历史消息
        await loadHistoryMessages()
      } else {
        // 会话不存在，跳转回角色选择页面
        message.error('会话不存在或已被删除')
        await router.push('/role-chat')
        return
      }
    } catch (error) {
      console.error('加载会话失败:', error)
      message.error('加载会话失败')
      // 如果加载失败，跳转回角色选择页面
      await router.push('/role-chat')
    }
  } else if (!conversationId) {
    // 如果没有会话ID，重置状态
    selectedChatRole.value = null
    chatMessages.value = []
    currentConversationId.value = null
    messagePageInfo.value = { pageNo: 1, hasMore: true, loading: false }
  }
}

// 监听路由参数变化
watch(
  () => route.params.conversationId,
  () => {
    loadConversationFromRoute()
  },
  { immediate: false }
)

// 监听props变化
watch(
  () => props.conversationId,
  () => {
    loadConversationFromRoute()
  },
  { immediate: false }
)

// 初始化时加载聊天角色和会话
onMounted(async () => {
  await Promise.all([
    loadChatRoles(),
    loadConversationHistory()
  ])
  await loadConversationFromRoute()

  // 等待DOM更新后添加滚动监听器
  await nextTick()
  if (chatMessagesAreaRef.value) {
    chatMessagesAreaRef.value.addEventListener('scroll', handleScroll)
  }
})

// 组件卸载时清理资源
onUnmounted(() => {
  // 移除滚动监听器
  if (chatMessagesAreaRef.value) {
    chatMessagesAreaRef.value.removeEventListener('scroll', handleScroll)
  }
})
</script>

<template>
  <div :style="styles.layout">
    <!-- 主要内容区域 -->
    <div :style="styles.mainArea">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-content">
          <h1 class="page-title">

            角色聊天
          </h1>
          <p class="page-description">选择一个角色开始1v1对话体验</p>
        </div>
      </div>

      <!-- 内容显示区域 -->
      <div :style="styles.contentArea">
        <!-- 角色选择界面 - 左右布局 -->
        <div v-if="!selectedChatRole" class="role-selection-layout">
          <!-- 左侧：历史对话列表 -->
          <ConversationSidebar
            :conversations="conversationHistory"
            :loading="loadingConversations"
            :active-conversation-id="currentConversationId"
            @select-conversation="selectConversation"
            @refresh="loadConversationHistory"
            @delete-conversation="handleDeleteConversation"
          />

          <!-- 右侧：角色卡片列表 -->
          <RoleCardList
            :roles="chatRoles"
            :loading="loadingChatRoles"
            @select-role="selectChatRole"
            @refresh="loadChatRoles"
          />
        </div>

        <!-- 聊天界面 - 左右布局 -->
        <div v-else class="chat-layout">
          <!-- 左侧：历史对话列表 -->
          <ConversationSidebar
            :conversations="conversationHistory"
            :loading="loadingConversations"
            :active-conversation-id="currentConversationId"
            @select-conversation="selectConversation"
            @refresh="loadConversationHistory"
            @delete-conversation="handleDeleteConversation"
          />

          <!-- 右侧：聊天区域 -->
          <div class="chat-main-area">
            <!-- 聊天头部 -->
            <div class="chat-header">
              <div class="flex items-center">
                <UserOutlined class="text-blue-purple-500 mr-2" />
                <div>
                  <Text strong>{{ selectedChatRole?.roleName }}</Text>
                  <div>
                    <Text type="secondary" class="text-sm">{{ selectedChatRole?.prompt }}</Text>
                  </div>
                </div>
              </div>
              <div class="space-x-2">
                <Button size="small" @click="clearChat" class="glass-btn glass-btn-blue">清空对话</Button>
                <Button size="small" @click="backToRoleSelection" class="glass-btn glass-btn-purple">换角色</Button>
              </div>
            </div>

            <!-- 聊天消息区域 -->
            <div class="chat-messages-area" ref="chatMessagesAreaRef">
              <div v-if="chatMessages.length === 0" class="text-center py-12">
                <MessageOutlined class="text-4xl text-blue-purple-300 mb-4" />
                <Text type="secondary" class="text-lg">
                  开始与{{ selectedChatRole?.roleName }}对话吧！
                </Text>
              </div>

              <div v-else class="space-y-4">
                <!-- 历史消息加载指示器 -->
                <div
                  v-if="messagePageInfo.loading && messagePageInfo.pageNo > 1"
                  class="loading-more-messages"
                >
                  <div class="loading-spinner"></div>
                  <span class="loading-text">加载更多消息...</span>
                </div>

                <div
                  v-for="message in chatMessages"
                  :key="message.id"
                  class="flex message-item"
                  :class="message.sender === 'user' ? 'justify-end' : 'justify-start'"
                >
                  <div
                    class="max-w-xs lg:max-w-md px-4 py-2 rounded-lg"
                    :class="{
                      'bg-blue-purple-500 text-white': message.sender === 'user',
                      'bg-white border border-gray-200': message.sender === 'ai'
                    }"
                  >
                    <div class="text-sm">{{ message.content }}</div>
                    <div class="flex items-center justify-between mt-2">
                      <div
                        class="text-xs opacity-70"
                        :class="message.sender === 'user' ? 'text-blue-purple-100' : 'text-gray-500'"
                      >
                        {{ message.timestamp.toLocaleTimeString() }}
                      </div>
                      <!-- AI消息的语音播放按钮 -->
                      <div v-if="message.sender === 'ai'" class="ml-2">
                        <TTSPlayButton
                          :message="message.content"
                          :show-text="false"
                          size="small"
                          type="text"
                          custom-class="text-gray-500 hover:text-blue-purple-500"
                          :voice-id="selectedChatRole?.voiceId || '5'"
                        />
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 正在输入指示器 -->
                <div v-if="isChatting" class="flex justify-start">
                  <div class="bg-white border border-gray-200 px-4 py-2 rounded-lg">
                    <div class="flex items-center space-x-1">
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 输入区域 -->
            <div class="chat-input-container">
              <div class="input-wrapper">
                <textarea
                  v-model="chatInput"
                  placeholder="输入消息"
                  :disabled="isChatting || isVoiceRecording"
                  @keydown.enter.prevent="sendChatMessage"
                  class="chat-input"
                  rows="1"
                ></textarea>
                <div class="input-actions">
                  <!-- 语音录制按钮 -->
                  <VoiceButton
                    :max-duration="60"
                    language="zh"
                    :disabled="isChatting"
                    @transcription-update="handleTranscriptionUpdate"
                    @recording-start="handleRecordingStart"
                    @recording-stop="handleRecordingStop"
                    @error="handleVoiceError"
                    class="voice-btn"
                  />

                  <!-- 深度思考切换按钮 -->
                  <Button
                    :type="isThinking ? 'primary' : 'default'"
                    size="large"
                    :disabled="isChatting"
                    @click="isThinking = !isThinking"
                    class="toggle-btn"
                    title="深度思考"
                  >
                    思考
                  </Button>

                  <!-- 网络搜索切换按钮 -->
                  <Button
                    :type="isSearch ? 'primary' : 'default'"
                    size="large"
                    :disabled="isChatting"
                    @click="isSearch = !isSearch"
                    class="toggle-btn"
                    title="网络搜索"
                  >
                    搜索
                  </Button>

                  <!-- 发送按钮 -->
                  <Button
                    type="primary"
                    shape="circle"
                    size="large"
                    :loading="isChatting"
                    :disabled="!chatInput.trim() && !isVoiceRecording"
                    @click="sendChatMessage"
                    class="send-btn"
                  >
                    <template #icon>
                      <SendOutlined />
                    </template>
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 自定义蓝紫色主题 */
.custom-blue-purple {
  --primary-color: #6366f1;
  --primary-hover: #5855eb;
  --primary-active: #4f46e5;
}

.text-blue-purple-300 {
  color: var(--blue-purple-300);
}

.text-blue-purple-400 {
  color: var(--blue-purple-400);
}

.text-blue-purple-500 {
  color: var(--blue-purple-500);
}

.text-blue-purple-600 {
  color: var(--blue-purple-600);
}

.border-blue-purple-200 {
  border-color: #e0e7ff;
}

.bg-blue-purple-50 {
  background-color: #f8faff;
}

.bg-blue-purple-100 {
  background-color: #f0f4ff;
}

.bg-blue-purple-500 {
  background-color: #6366f1;
}

/* Ant Design Card 样式覆盖 */
:deep(.ant-card) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

:deep(.ant-card:hover) {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border-color: var(--primary-color, #6366f1);
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 16px 24px;
}

:deep(.ant-card-body) {
  padding: 24px;
}

.ant-card-small > .ant-card-head {
  padding: 8px 12px;
  min-height: auto;
}

.ant-card-small > .ant-card-body {
  padding: 12px;
}

/* 角色选择界面的左右布局 */
.role-selection-layout {
  display: flex;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

.role-selection-layout > :first-child {
  flex: 0 0 300px; /* 左侧对话列表固定宽度 */
  min-width: 300px;
  max-width: 300px;
}

.role-selection-layout > :last-child {
  flex: 1; /* 右侧角色列表自适应剩余宽度 */
  min-width: 0;
  overflow: hidden;
}

/* 聊天界面的左右布局 */
.chat-layout {
  display: flex;
  height: 100%;
  width: 100%;
  gap: 16px;
  overflow: hidden;
}

.chat-layout > :first-child {
  flex: 0 0 300px; /* 左侧对话列表固定宽度 */
  min-width: 300px;
  max-width: 300px;
}

.chat-main-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 0;
  overflow: hidden;
}

/* 聊天头部 */
.chat-header {
  padding: 16px;
  background: #f8faff;
  border-radius: 12px 12px 0 0;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

/* 聊天消息区域 */
.chat-messages-area {
  flex: 1;
  padding: 16px;
  background: #f8f9fa;
  overflow-y: auto;
  min-height: 0;
}

/* 聊天输入区域样式 */
.chat-input-container {
  padding: 16px;
  background: #ffffff;
  border-top: 1px solid #f0f0f0;
  border-radius: 0 0 12px 12px;
  flex-shrink: 0;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 24px;
  border: 1px solid #e9ecef;
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
}

.input-wrapper:hover {
  border-color: #6366f1;
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
}

.input-wrapper:focus-within {
  border-color: #6366f1;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.chat-input {
  flex: 1;
  height: 100%;
  border: none;
  outline: none;
  background: transparent;
  font-size: 16px;
  line-height: 1.5;
  resize: none;
  min-height: 24px;
  max-height: 120px;
  overflow-y: auto;
  font-family: inherit;
  padding: 8px 0;
  vertical-align: center;
}

.chat-input:focus {
  outline: none;
  border: none;
  box-shadow: none;
}

.chat-input::placeholder {
  color: #9ca3af;
}

.input-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

/* 语音按钮样式 */
:deep(.voice-btn .voice-button) {
  width: 40px;
  height: 40px;
  border: none;
  background: #f3f4f6;
  color: #6b7280;
  transition: all 0.2s ease;
}

:deep(.voice-btn .voice-button:hover) {
  background: #e5e7eb;
  color: #374151;
  transform: scale(1.05);
}

:deep(.voice-btn .voice-button.recording) {
  background: #ef4444;
  color: white;
  animation: pulse 1.5s infinite;
}

/* 切换按钮样式 */
.toggle-btn {
  min-width: 60px;
  height: 40px;
  transition: all 0.2s ease;
  font-size: 14px;
  padding: 0 12px;
}

.toggle-btn:hover {
  transform: scale(1.05);
}

/* 发送按钮样式 */
.send-btn {
  width: 40px;
  height: 40px;
  background: #6366f1 !important;
  border-color: #6366f1 !important;
  transition: all 0.2s ease;
}

.send-btn:hover {
  background: #5855eb !important;
  border-color: #5855eb !important;
  transform: scale(1.05);
}

.send-btn:disabled {
  background: #d1d5db !important;
  border-color: #d1d5db !important;
  transform: none;
}

/* 脉冲动画 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

/* 输入按钮组样式 */
.input-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 磨砂玻璃按钮样式 */
.glass-btn {
  position: relative;
  border: none !important;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 8px !important;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.glass-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 8px;
  padding: 1px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0.1));
  mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  mask-composite: exclude;
  -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
  -webkit-mask-composite: xor;
}

/* 浅蓝色磨砂玻璃按钮 */
.glass-btn-blue {
  background: rgba(147, 197, 253, 0.3) !important;
  color: #1e40af !important;
  border: 1px solid rgba(147, 197, 253, 0.4) !important;
}

.glass-btn-blue:hover {
  background: rgba(147, 197, 253, 0.4) !important;
  color: #1d4ed8 !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.glass-btn-blue:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.15);
}

/* 浅紫色磨砂玻璃按钮 */
.glass-btn-purple {
  background: rgba(196, 181, 253, 0.3) !important;
  color: #6d28d9 !important;
  border: 1px solid rgba(196, 181, 253, 0.4) !important;
}

.glass-btn-purple:hover {
  background: rgba(196, 181, 253, 0.4) !important;
  color: #7c3aed !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(139, 92, 246, 0.2);
}

.glass-btn-purple:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(139, 92, 246, 0.15);
}

/* 磨砂玻璃按钮文字样式 */
.glass-btn span {
  position: relative;
  z-index: 1;
}

/* 角色卡片样式 */
.role-card {
  transition: all 0.2s ease;
}

.role-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
}

/* 会话卡片样式 */
.conversation-card {
  transition: all 0.2s ease;
}

.conversation-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0;
  padding: 32px 32px 24px 32px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.8) 100%);
  border-radius: 16px 16px 0 0;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-bottom: none;
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  color: #1a1a1a;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 16px;
  line-height: 1.5;
}

/* 历史消息加载指示器 */
.loading-more-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background: #f8faff;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #6366f1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 12px;
  color: #6b7280;
}
</style>
